<template>
  <div class="flex flex-col h-full p-4">
    <!-- 详情页面 -->
    <BMSFaultDetail v-if="showDetailsRef" :fault-id="detailId" @go-back="goBackToList" />

    <!-- BMS Fault Container with white background -->
    <div v-else class="flex-1 flex flex-col bg-white rounded-lg shadow p-6 min-h-0">
      <!-- Filter section -->
      <div class="mb-6">
        <!-- 上栏筛选条件 -->
        <div class="flex items-center gap-4 mb-4">
          <el-input v-model="filters.searchText" placeholder="Battery Pack SN/Device SN" clearable class="w-70!" @input="debouncedSearch()">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>

          <el-select v-model="filters.status" placeholder="All status" clearable class="w-44!">
            <el-option v-for="item in faultStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-select v-model="filters.batteryType" placeholder="All battery type" clearable class="w-44!">
            <el-option v-for="item in batteryTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-select v-model="filters.alertName" placeholder="All alert name" clearable class="w-44!">
            <el-option v-for="item in alertNameOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>

        <!-- 下栏筛选条件 -->
        <div class="flex items-center gap-4">
          <div class="flex items-center">
            <span class="mr-2">Occurrence time:</span>
            <el-date-picker v-model="occurrenceTimeRange" type="daterange" range-separator="→"
              start-placeholder="Start date" end-placeholder="End date" class="w-64!" />
          </div>

          <div class="flex items-center">
            <span class="mr-2">Detect time:</span>
            <el-date-picker v-model="detectTimeRange" type="daterange" range-separator="→"
              start-placeholder="Start date" end-placeholder="End date" class="w-64!" />
          </div>

          <div class="flex ml-auto">
            <el-button type="default" @click="resetFilters">Reset</el-button>
            <el-button type="primary" @click="searchFaults">Search</el-button>
          </div>
        </div>
      </div>

      <!-- Table section -->
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="displayedFaultList.length > 0"
        @retry="retryFetch"
      >
        <BMSFaultTable
          :fault-data="displayedFaultList"
          :pagination="pagination"
          @page-change="handleCurrentChange"
          @size-change="handleSizeChange"
          @details="handleDetails"
          @close="handleClose"
          class="flex-1"
        />
      </PageState>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, onDeactivated } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { type BMSFaultItem, faultStatusOptions, alertNameOptions, batteryTypeOptions } from "./data";
import { bmsApi } from "@/api/bms";
import BMSFaultTable from "./components/BMSFaultTable.vue";
import BMSFaultDetail from "./components/BMSFaultDetail.vue";
import PageState from "@/components/base/PageState.vue";
import { useDebounce } from "@/utils/utils";

// 切换到详情页面
const showDetailsRef = ref(false);

// 详情页面id
const detailId = ref("");

// 筛选条件定义
const occurrenceTimeRange = ref([]);
const detectTimeRange = ref([]);
const filters = reactive({
  searchText: "",
  status: "",
  batteryType: "",
  alertName: "",
  predictedTime: "",
  detectTimeStart: "",
  detectTimeEnd: "",
  occurrenceTimeStart: "",
  occurrenceTimeEnd: ""
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// BMS故障数据
const bmsFaults = ref<BMSFaultItem[]>([]);

// 当前页显示的故障数据（直接使用API返回的数据）
const displayedFaultList = computed(() => {
  return bmsFaults.value;
});

// 获取故障列表
const fetchFaultList = async () => {
  loading.value = true;
  errorMessage.value = "";
  
  try {
    // 构建查询参数
    const params: any = {
      page: pagination.currentPage.toString(),
      limit: pagination.pageSize.toString()
    };

    // 添加筛选条件
    if (filters.searchText) {
      // 将搜索文本同时作为 batteryPackSn 和 deviceSn 参数传递
      params.batteryPackSn = filters.searchText;
      params.deviceSn = filters.searchText;
    }
    if (filters.status) {
      params.status = filters.status;
    }
    if (filters.batteryType) {
      params.batteryType = filters.batteryType;
    }
    if (filters.alertName) {
      params.alertName = filters.alertName;
    }
    if (filters.predictedTime) {
      params.predictedTime = filters.predictedTime;
    }
    if (filters.detectTimeStart) {
      params.detectTimeStart = filters.detectTimeStart;
    }
    if (filters.detectTimeEnd) {
      params.detectTimeEnd = filters.detectTimeEnd;
    }
    if (filters.occurrenceTimeStart) {
      params.occurrenceTimeStart = filters.occurrenceTimeStart;
    }
    if (filters.occurrenceTimeEnd) {
      params.occurrenceTimeEnd = filters.occurrenceTimeEnd;
    }
    
    console.log('调用BMS故障API:', params);
    const response = await bmsApi.getFaultPage(params);
    
    if (response.code === 0) {
      bmsFaults.value = response.data.list || [];
      pagination.total = response.data.total || 0;
      console.log('BMS故障列表数据获取成功:', response.data);
    } else {
      throw new Error(response.msg || '获取数据失败');
    }
  } catch (error: any) {
    console.error('获取BMS故障列表失败:', error);
    errorMessage.value = error.message || '网络请求失败，请重试';
    ElMessage.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 方法
const resetFilters = () => {
  filters.searchText = "";
  filters.status = "";
  filters.batteryType = "";
  filters.alertName = "";
  filters.predictedTime = "";
  filters.detectTimeStart = "";
  filters.detectTimeEnd = "";
  filters.occurrenceTimeStart = "";
  filters.occurrenceTimeEnd = "";
  occurrenceTimeRange.value = [];
  detectTimeRange.value = [];
  pagination.currentPage = 1;
  fetchFaultList();
};

const searchFaults = () => {
  // 重置分页
  pagination.currentPage = 1;
  fetchFaultList();
};

// 防抖搜索
const debouncedSearch = useDebounce(() => {
  searchFaults();
}, 500, { leading: false, trailing: true });

// 监听时间范围变化
watch(occurrenceTimeRange, (newRange: any) => {
  if (newRange && newRange.length === 2) {
    filters.occurrenceTimeStart = newRange[0].toISOString().slice(0, 19);
    filters.occurrenceTimeEnd = newRange[1].toISOString().slice(0, 19);
  } else {
    filters.occurrenceTimeStart = "";
    filters.occurrenceTimeEnd = "";
  }
});

watch(detectTimeRange, (newRange: any) => {
  if (newRange && newRange.length === 2) {
    filters.detectTimeStart = newRange[0].toISOString().slice(0, 19);
    filters.detectTimeEnd = newRange[1].toISOString().slice(0, 19);
  } else {
    filters.detectTimeStart = "";
    filters.detectTimeEnd = "";
  }
});

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  fetchFaultList();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchFaultList();
};

const handleDetails = (row: BMSFaultItem) => {
  // 跳转到详情页面
  showDetailsRef.value = true;
  detailId.value = row.id;
};

const handleClose = async (row: BMSFaultItem) => {
  try {
    const response = await bmsApi.closeFault({ id: row.id });
    if (response.code === 0) {
      ElMessage.success(`故障已关闭: ${row.batteryPackSn}`);
      // 重新获取列表数据
      fetchFaultList();
    } else {
      throw new Error(response.msg || '关闭故障失败');
    }
  } catch (error: any) {
    console.error('关闭故障失败:', error);
    ElMessage.error(error.message || '关闭故障失败，请重试');
  }
};

const goBackToList = () => {
  showDetailsRef.value = false;
  detailId.value = "";
};

onDeactivated(() => {
  showDetailsRef.value = false;
  detailId.value = "";
});

// 状态与重试
const loading = ref(false);
const errorMessage = ref("");

const retryFetch = () => {
  errorMessage.value = "";
  fetchFaultList();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchFaultList();
});
</script>

<style lang="scss" scoped>
/* 样式 */
</style>
